const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = ({ isDev }) => {
  /** @type {import('webpack').Configuration} */
  return {
    module: {
      // loader处理文件
      rules: [
        {
          oneOf: [
            {
              exclude: /node_modules/,
              test: /\.tsx?$/,
              use: {
                loader: "babel-loader",
                options: {
                  cacheDirectory: true, // 缓存
                  plugins: [
                    isDev && "react-refresh/babel", // 热更新
                  ].filter(Boolean),
                  presets: [
                    [
                      "@babel/preset-env", // 转换语法
                      {
                        corejs: { version: "3.19,1", proposals: true }, // 转换api
                        useBuiltIns: "usage",
                      },
                    ],
                    "@babel/preset-typescript", // 转换ts
                    "@babel/preset-react", // 转换jsx
                  ],
                },
              },
            },
            {
              test: /\.module\.scss$/,
              use: [
                // 开发环境添加到style中 其它环境输出为单独的css文件
                isDev ? "style-loader" : MiniCssExtractPlugin.loader,
                {
                  loader: "css-loader", // 将所有css文件处理为commonjs模块
                  options: { modules: true },
                },
                "postcss-loader", // 根据package.json browserslist选项给css加前缀
                "sass-loader", // 处理sass使其变为css
              ],
            },
            {
              test: /\.scss$/,
              use: [
                // 开发环境添加到style中 其它环境输出为单独的css文件
                isDev ? "style-loader" : MiniCssExtractPlugin.loader,
                "css-loader", // 将所有css文件处理为commonjs模块
                "postcss-loader", // 根据package.json browserslist选项给css加前缀
                "sass-loader", // 处理sass使其变为css
              ],
            },
            {
              test: /\.(png|svg|jpg|jpeg|gif)$/i,
              type: "asset/resource",
              use: [
                !isDev && {
                  loader: "image-webpack-loader", // 压缩图片
                  options: {
                    mozjpeg: {
                      progressive: true,
                    },
                    optipng: {
                      enabled: false,
                    },
                    pngquant: {
                      quality: [0.65, 0.9],
                      speed: 4,
                    },
                    gifsicle: {
                      interlaced: false,
                    },
                    webp: {
                      quality: 75,
                    },
                  },
                },
              ].filter(Boolean),
            },
            {
              test: /\.(woff|woff2|eot|ttf|otf)$/i,
              type: "asset/resource",
            },
          ],
        },
      ],
    },
  };
};
